package org.onionframework.faces.web.action.support;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import javax.faces.event.ValueChangeEvent;

import org.richfaces.component.UIDataTable;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * 处理行选择逻辑的辅助类，对应前端的dataTable
 * 
 * @author allan
 *
 * @param <T>
 */
@Component("dataTable")
@Scope("request")
public class CommonDataTableBean {
	
	private UIDataTable table;
	
	private Set<Integer> selectedRows;

	public UIDataTable getTable() {
		return table;
	}

	/**
	 * dataTable的数据发生变化的时候（整体被替换），清空选择状态
	 * 
	 * @param dataTable
	 */
	public void setTable(UIDataTable dataTable) {
		this.table = dataTable;
	}
	
	public void cleanSelection(){
		if(this.selectedRows != null)
			this.selectedRows.clear();
	}
	
	public void selectChanged(ValueChangeEvent event){
		if(this.getSelectedRows() == null)
			this.setSelectedRows(new TreeSet<Integer>());
		
		try {
			Integer key = Integer.parseInt(event.getComponent().getAttributes().get("styleClass").toString());
			if((Boolean)event.getNewValue()){
				this.getSelectedRows().add(key);
				event.getComponent().getAttributes().put("value", false);
			}else
				this.getSelectedRows().remove(key);			
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<?> getSelections(){
		List list = new ArrayList<Object>();
		
		if(this.getSelectedRows() == null)
			return list;
		
		Iterator<Integer> keys = this.getSelectedRows().iterator();
		
		while(keys.hasNext()){
			Object o = keys.next();
			this.table.setRowKey(o);
			if(this.table.isRowAvailable())
				list.add(this.table.getRowData());
		}
		
		this.table.setRowKey(null);
		
		return list;
	}
	
	public Object getSelected(){
		
		Iterator<Integer> keys = this.getSelectedRows().iterator();
		
		Object value;
		while(keys.hasNext())
		{
			this.table.setRowKey(keys.next());
			if(this.table.isRowAvailable()){
				value = this.table.getRowData();
				this.table.setRowKey(null);
				return value;
			}else
				this.table.setRowKey(null);
		}
		
		return null;
	}

	/**
	 * @return the selectedRows
	 */
	protected Set<Integer> getSelectedRows() {
		return selectedRows;
	}

	/**
	 * @param selectedRows the selectedRows to set
	 */
	protected void setSelectedRows(Set<Integer> selectedRows) {
		this.selectedRows = selectedRows;
	}
	
	/**
	 * @return 当前已选条目数量
	 */
	public int getSelectedCount(){
		return this.getSelectedRows() == null ? 0 : this.getSelectedRows().size();
	}
}
